//
//  decisionAppDelegate.m
//  decision
//
//  Created by Zhiguo on 03.02.10.
//  Copyright Home 2010. All rights reserved.
//

#import "decisionAppDelegate.h"
#import "RootViewController.h"
#import "decisionPoint.h"

@interface decisionAppDelegate (Private)

- (void) createEditableCopyOfDatabaseIfNeeded;
- (void) initializeDatabase;

@end

@implementation decisionAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize decisionPoints;

#pragma mark -
#pragma mark Application lifecycle

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    
    // Override point for customization after app launch    
	[self createEditableCopyOfDatabaseIfNeeded];
	[self initializeDatabase];
	[window addSubview:[navigationController view]];
    [window makeKeyAndVisible];
}


- (void)applicationWillTerminate:(UIApplication *)application {
	// Save data if appropriate
}

- (void) createEditableCopyOfDatabaseIfNeeded{
	BOOL success;
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentDirectory = [paths objectAtIndex:0];
	NSString *writableDBPath = [documentDirectory stringByAppendingPathComponent:@"goodP.sqlite"];
	success = [fileManager fileExistsAtPath:writableDBPath];
	
	if(success) return;
	NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"goodP.sqlite"];
	success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
	
	if(!success){
		
		NSAssert1(0, @"failed to create writeable database file with message '%@'. ", [error localizedDescription]);
	}
}

-(void) initializeDatabase {
	NSMutableArray *decisionPointsArray = [[NSMutableArray alloc] init];
	self.decisionPoints = decisionPointsArray;
	[decisionPointsArray release];
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentDirectory = [paths objectAtIndex:0];
	NSString *path = [documentDirectory stringByAppendingPathComponent:@"goodP.sqlite"];
	
	if(sqlite3_open([path UTF8String], &database) == SQLITE_OK){
		const char *sql = "SELECT id from decision";
		sqlite3_stmt  *statement;
		if(sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK){
			while(sqlite3_step(statement) == SQLITE_ROW){
				int pKey = sqlite3_column_int(statement, 0);
				decisionPoint *dp = [[decisionPoint alloc] initWithPid:pKey database:database];
				[self.decisionPoints addObject:dp];
				[dp release];
			}
		}
		sqlite3_finalize(statement);
	}else {
		sqlite3_close(database);
		NSAssert1(0, @"failed to open database with message '%s'. ", sqlite3_errmsg(database));
	}
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	[navigationController release];
	[window release];
	[super dealloc];
}


@end

